package com.zgc.zkinfo;

import com.zgc.view.controller.ProgressAlertCtrl;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import org.apache.curator.framework.CuratorFramework;

public class ZkService extends Service<CuratorFramework> {

    private ZkTask zkTask;

    public ZkService() {
    }

    /**
     * Service 启动之后才有值，否则为空
     *
     * @return ZkTask
     */
    public ZkTask getTask() {
        return zkTask;
    }


    public ZkConnectionInfo getZkConnectInfo() {
        if (getTask() == null) {
            return null;
        }
        return getTask().getZkConnectInfo();
    }

    @Override
    protected Task<CuratorFramework> createTask() {
        return getTask();
    }


    public void startAndAlert(ZkConnectionInfo client, ProgressAlertCtrl progressAlertCtrl) {
        progressAlertCtrl.showProgressAlert(client.getHost(), this);

        // 绑定message
        progressAlertCtrl.getAlertMessage().textProperty().bind(this.messageProperty());

        this.zkTask = new ZkTask(client);
        // 判断状态启动
        if (State.READY.equals(getState())) {
            this.start();
        } else {
            this.restart();
        }
        // 工作进度监听
        this.stateProperty().addListener((obv, ov, nv) -> {
            switch (nv) {
                case SUCCEEDED -> progressAlertCtrl.setSuccessProgressColor();
                case FAILED -> progressAlertCtrl.setFailProgressColor();
                default -> progressAlertCtrl.setDefaultProgressColor();
            }
        });
    }
}
